<template>
  <div id="patientManagePage">
    <a-flex justify="space-between">
      <h2>病人管理</h2>
    </a-flex>
    <div style="margin-bottom: 16px" />

    <a-row style="margin-top: 20px" justify="center" gutter="16">
      <a-col :span="5">
        <a-card style="border: #eee solid; min-height: 500px">
          <template #title>
            <a-flex justify="space-between" style="margin-top: 10px">
              <h2><strong>病人分组</strong></h2>
              <a-space>
                <a-button type="primary" ghost @click="addGroupFlag = true">创建分组</a-button>
              </a-space>
            </a-flex>
            <a-divider
              style="margin-top: 5px; height: 2px; border-color: #bbbbbb; margin-bottom: 5px"
            />
            <a-flex justify="space-between" style="margin-top: 2px; margin-bottom: 5px">
              <a-button type="primary" @click="showGroupUpdateModal">编辑分组</a-button>
              <a-popconfirm title="确认删除分组吗?" @confirm="deleteGroup">
                <a-button danger ghost>删除分组</a-button>
              </a-popconfirm>
            </a-flex>
          </template>
          <!--          树形结构哦-->
          <div>
            <a-input-search
              v-model:value="searchValue"
              style="margin-bottom: 8px"
              placeholder="Search"
            />
            <a-tree
              show-line
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :tree-data="gData"
              @select="selectNode"
              @expand="onExpand"
              style="font-size: 16px"
            >
              <template #title="{ title }">
                <span v-if="title.indexOf(searchValue) > -1">
                  {{ title.substring(0, title.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{ title.substring(title.indexOf(searchValue) + searchValue.length) }}
                </span>
                <span v-else>{{ title }}</span>
              </template>
            </a-tree>
          </div>
        </a-card>
      </a-col>
      <a-col :span="19">
        <a-card style="border: #eee solid">
          <div style="font-size: 18px">
            <a-flex justify="space-between">
              <!--    搜索表单-->
              <a-form layout="inline" :model="searchParams" @finish="doSearch">
                <a-form-item label="病人名称">
                  <a-input
                    v-model:value="searchParams.patientName"
                    placeholder="输入病人名称"
                    allow-clear
                  />
                </a-form-item>
                <a-form-item label="备注">
                  <a-input v-model:value="searchParams.note" placeholder="输入备注" allow-clear />
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" html-type="submit">搜索</a-button>
                </a-form-item>
              </a-form>
              <a-button type="primary" @click="showAddModal">创建病例</a-button>
            </a-flex>

            <div style="margin-bottom: 16px" />
            <a-table
              :columns="columns"
              :data-source="dataTableList"
              :pagination="pagination"
              @change="doTableChange"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'groupName'">
                  {{ record.groupId == -1 ? '全部' : record.patientGroupVO.groupName }}
                </template>
                <template v-if="column.dataIndex === 'createTime'">
                  {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                </template>
                <template v-if="column.dataIndex === 'predictStatus'">
                  <a-tag
                    :color="
                      FILE_TRAIN_CREATE_STATUS_COLOR_ENUM[
                        record.filePredictVO?.predictStatus ?? 'Waiting'
                      ]
                    "
                  >
                    {{ record.filePredictVO?.predictStatus ?? 'Waiting' }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-space>
                    <a-button type="primary" @click="showPatientDetail(record)">查看详情</a-button>
                    <a-popconfirm
                      v-if="dataTableList.length && record.userRole !== 'admin'"
                      title="确定删除嘛？"
                      @confirm="doTableDelete(record.id)"
                    >
                      <a-button danger>删除</a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!--    添加分组弹窗-->
    <a-modal
      v-model:visible="addGroupFlag"
      title="添加分组"
      style="margin: 0 auto"
      @ok="doAddGroup"
    >
      <a-form :model="groupAddParams" @finish="doSearch" style="margin-top: 20px">
        <a-form-item label="分组名称">
          <a-input
            v-model:value="groupAddParams.groupName"
            placeholder="请输入分组名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="父级分组">
          <a-tree-select
            v-model:value="groupAddParams.parentId"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择父级分组"
            allow-clear
            tree-default-expand-all
            :tree-data="treeData"
            tree-node-filter-prop="label"
          >
            <template #title="{ value: val, label }">
              <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
              <template v-else>{{ label }}</template>
            </template>
          </a-tree-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!--    修改分组弹窗-->
    <a-modal
      v-model:visible="updateGroupFlag"
      title="添加分组"
      style="margin: 0 auto"
      @ok="doUpdateGroup"
    >
      <a-form :model="groupUpdateParams" style="margin-top: 20px">
        <a-form-item label="分组id">
          <a-input v-model:value="groupUpdateParams.id" disabled />
        </a-form-item>
        <a-form-item label="分组名称">
          <a-input
            v-model:value="groupUpdateParams.groupName"
            placeholder="请输入分组名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="父级分组">
          <a-tree-select
            v-model:value="groupUpdateParams.parentId"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择父级分组"
            allow-clear
            tree-default-expand-all
            :tree-data="treeData"
            tree-node-filter-prop="label"
          >
            <template #title="{ value: val, label }">
              <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
              <template v-else>{{ label }}</template>
            </template>
          </a-tree-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!--    病人详情弹窗-->
    <a-modal
      v-model:visible="patientDetailFlag"
      style="margin: 0 auto; width: 60%"
      @ok="patientDetailFlag = false"
    >
      <template #title>
        <h1>病人详情信息</h1>
      </template>
      <!--      {{ selectedPatient }}-->
      <a-flex justify="space-between">
        <h2><strong> 病人基本信息： </strong></h2>
        <a-space>
          <a-button
            v-if="updatePatientFlag"
            type="primary"
            @click="
              () => {
                updatePatientFlag = false
              }
            "
            >修改病人信息
          </a-button>
          <a-space v-else>
            <a-button ghost type="primary" @click="doPatientUpdate">确认修改</a-button>
            <a-button
              ghost
              danger
              @click="
                () => {
                  updatePatientParam.groupId = selectedPatient.groupId
                  updatePatientParam.id = selectedPatient.id
                  updatePatientParam.patientName = selectedPatient.patientName
                  updatePatientParam.note = selectedPatient.note
                  updatePatientFlag = true
                }
              "
              >取消
            </a-button>
          </a-space>
        </a-space>
      </a-flex>

      <a-form :model="updatePatientParam" style="margin-top: 20px">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="记录编号">
              <a-input v-model:value="updatePatientParam.id" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="病人名称">
              <a-input
                v-model:value="updatePatientParam.patientName"
                placeholder="请输入病人名称"
                allow-clear
                :disabled="updatePatientFlag"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="备注信息">
              <a-textarea
                v-model:value="updatePatientParam.note"
                placeholder="请输入备注"
                allow-clear
                :auto-size="{
                  minRows: 1,
                  maxRows: 3,
                }"
                :disabled="updatePatientFlag"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="分组类别">
              <a-tree-select
                v-model:value="updatePatientParam.groupId"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="请选择父级分组"
                allow-clear
                tree-default-expand-all
                :tree-data="treeData"
                tree-node-filter-prop="label"
                :disabled="updatePatientFlag"
              >
                <template #title="{ value: val, label }">
                  <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
                  <template v-else>{{ label }}</template>
                </template>
              </a-tree-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <!--      预测信息-->
      <h2><strong> 预测基本信息： </strong></h2>
      <a-descriptions title="基本参数信息">
        <a-descriptions-item
          v-for="variable in selectedPatient.filePredictVO?.predictParams"
          :key="variable.columnNumber"
          :label="
            `第${Number(variable.columnNumber) + 1}列,` +
            featureMap[Number(variable.columnNumber) + 1]
          "
        >
          {{ variable?.param ?? '--' }}
        </a-descriptions-item>
      </a-descriptions>

      <a-descriptions title="预测结果信息">
        <a-descriptions-item label="预测状态">
          <a-tag
            v-if="selectedPatient.filePredictVO?.predictResult?.code === 0"
            :color="
              FILE_TRAIN_CREATE_STATUS_COLOR_ENUM[
                selectedPatient.filePredictVO?.predictStatus ?? 'Waiting'
              ]
            "
            >{{ selectedPatient.filePredictVO?.predictStatus ?? 'Waiting' }}
          </a-tag>
          <a-tag v-else color="red">Error</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="预测信息">
          {{ selectedPatient.filePredictVO?.predictResult?.message ?? '--' }}
        </a-descriptions-item>
        <a-descriptions-item :label="`${targetMap[targetColumn]} 预测结果`">
          {{ selectedPatient.filePredictVO?.predictResult?.data ?? '--' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!--    病人添加弹窗-->
    <a-modal
      v-model:visible="showAddPatientFlag"
      style="margin: 0 auto; width: 60%"
      @ok="doAddPatient"
    >
      <template #title>
        <h1>病人添加</h1>
      </template>

      <h2><strong> 病人基本信息填写： </strong></h2>

      <a-form :model="addPatientParams" style="margin-top: 20px">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="病人名称">
              <a-input
                v-model:value="addPatientParams.patientName"
                placeholder="请输入病人名称"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="分组类别">
              <a-tree-select
                v-model:value="addPatientParams.groupId"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="请选择父级分组"
                allow-clear
                tree-default-expand-all
                :tree-data="treeData"
                tree-node-filter-prop="label"
              >
                <template #title="{ value: val, label }">
                  <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
                  <template v-else>{{ label }}</template>
                </template>
              </a-tree-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item label="备注信息">
              <a-textarea
                v-model:value="addPatientParams.note"
                placeholder="请输入备注"
                allow-clear
                :auto-size="{
                  minRows: 1,
                  maxRows: 3,
                }"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <h2>
        <strong> 选择训练模型： </strong>
      </h2>

      <a-flex justify="space-between">
        <a-space>
          <span style="font-size: 16px">选择模型id：</span>
          <span> {{ addPatientParams.filePredictAddRequest?.trainId ?? '未选择' }}</span>
        </a-space>

        <a-button @click="showDrawer" type="primary">选择模型</a-button>
      </a-flex>

      <div v-if="addPatientParams?.filePredictAddRequest?.trainId">
        <h2><strong> 填写预测数据： </strong></h2>

        <a-descriptions title="预测简介">
          <a-descriptions-item label="简介">
            <a-input v-model:value="addPatientParams.filePredictAddRequest.introduction" style="width: 80%" allow-clear />
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions title="基本参数信息">
          <a-descriptions-item
            v-for="(variable, index) in variablesPredictParamsList"
            :key="variable.columnNumber"
            :label="
                `第${Number(variable.columnNumber)}列,` +
                variable.variablesName
              "
          >
            <a-input v-model:value="addPatientParams.filePredictAddRequest.predictParams[index].param" style="width: 90%" allow-clear />
          </a-descriptions-item>
        </a-descriptions>

      </div>
    </a-modal>



<!--    选择模型-->
    <a-drawer width="70%" title="选择模型" placement="right" :open="open" @close="onClose">
      <template #extra>
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </template>

      <a-space>
        <h3>所选择的训练ID</h3>
        <a :href="'/train/' + selectedTrainId" target="_blank" style="color: red"
          ><h4>{{ selectedTrainId }}</h4></a
        >
      </a-space>

      <div style="margin-bottom: 16px" />
      <!--    搜索表单-->
      <a-form layout="inline" :model="searchTrainParams" @finish="doTrainSearch">
        <a-form-item label="文件id">
          <a-input v-model:value="searchTrainParams.fileId" placeholder="输入文件Id" allow-clear />
        </a-form-item>
        <a-form-item label="模型">
          <a-input
            v-model:value="searchTrainParams.model"
            placeholder="输入模型名称名称"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
      </a-form>
      <div style="margin-bottom: 16px" />

      <a-table
        :columns="trainColumns"
        :data-source="dataTrainList"
        :pagination="trainPagination"
        @change="doTrainTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'id'">
            <a :href="'/train/' + record.id" target="_blank">{{ record.id }}</a>
          </template>
          <template v-if="column.dataIndex === 'fileId'">
            <a :href="'/file/' + record.fileId" target="_blank">{{ record.fileId }}</a>
          </template>
          <template v-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-if="column.dataIndex === 'fileName'">
            {{ record.file.name }}
          </template>

          <template v-else-if="column.key === 'action'">
            <a-button
              type="primary"
              ghost
              @click="
                () => {
                  selectedTrainId = record.id
                }
              "
              >选择
            </a-button>
          </template>
        </template>
      </a-table>
    </a-drawer>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { message, type TreeProps, type TreeSelectProps } from 'ant-design-vue'
import {
  addPatientGroupUsingPost,
  deletePatientGroupUsingPost,
  getPatientGroupByIdUsingGet,
  getPatientGroupUsingGet,
  updatePatientGroupUsingPost,
} from '@/api/patientGroupController.ts'
import dayjs from 'dayjs'
import {
  addPatientUsingPost,
  deletePatientUsingPost,
  listPatientVoByPageUsingPost,
  updatePatientUsingPost
} from '@/api/patientController.ts'
import {
  FILE_TRAIN_CREATE_STATUS_COLOR_ENUM,
  FILE_TRAIN_CREATE_STATUS_ENUM,
} from '@/constant/file.ts'
import { getFileVariablesListUsingPost } from '@/api/filePredictController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { listFileTrainVoByPageUsingPost } from '@/api/fileTrainController.ts'
import { add } from 'zrender/lib/core/vector'

const addGroupFlag = ref(false)
const updateGroupFlag = ref(false)

const groupAddParams = reactive<API.PatientGroupAddRequest>({
  groupName: '',
  parentId: -1,
}) // 分组添加参数

const groupUpdateParams = reactive<API.PatientGroupUpdateRequest>({
  id: 0,
  groupName: '',
  parentId: -1,
}) // 分组添加参数

const doSearch = () => {
  fetchData()
  return
}
// ----------- 处理树形数据

const groupId = ref()
const dfs = (original: API.Category): TreeProps['treeData'] => {
  const tns: TreeProps['treeData'] = [] // 在递归中每次创建新的数组
  for (let i = 0; i < original?.children?.length ?? 0; i++) {
    const node = original.children[i]
    const key = node.id
    const currentNode = { key: key, title: node.name }

    if (node.children.length > 0) {
      currentNode.children = dfs(node) // 递归调用 dfs 来处理子节点
    }

    tns.push(currentNode)
  }
  return tns
}
const treeData = ref<TreeSelectProps['treeData']>([])

const transformData = (data) => {
  return data.map((item) => {
    let transformedItem = {
      value: item.key,
      label: item.title,
    }

    if (item.children) {
      transformedItem.children = transformData(item.children)
    }

    return transformedItem
  })
}

const generateData = (origin: API.Category) => {
  const genData: TreeProps['treeData'] = []
  for (let i = 0; i < origin.length; i++) {
    const node = origin[i]
    const key = node.id
    const currentNode = { key: key, title: node.name }

    if (node.children.length > 0) {
      currentNode.children = dfs(node) // 递归调用 dfs 来处理子节点
    }

    genData.push(currentNode)
  }
  gData.value = genData
  generateList(gData.value)
  treeData.value = transformData(gData.value)
}

const dataList = ref<TreeProps['treeData']>([])
const generateList = (data: TreeProps['treeData']) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const key = node.key
    dataList.value.push({ key, title: node.title })
    if (node.children) {
      generateList(node.children)
    }
  }
}

const getParentKey = (
  key: string | number,
  tree: TreeProps['treeData'],
): string | number | undefined => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}
const expandedKeys = ref<(string | number)[]>([])
const searchValue = ref<string>('')
const autoExpandParent = ref<boolean>(true)
const gData = ref<TreeProps['treeData']>([])

const onExpand = (keys: string[]) => {
  expandedKeys.value = keys
  autoExpandParent.value = false
}

watch(searchValue, (value) => {
  const expanded = dataList.value
    .map((item: TreeProps['treeData'][number]) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, gData.value)
      }
      return null
    })
    .filter((item, i, self) => item && self.indexOf(item) === i)
  expandedKeys.value = expanded
  searchValue.value = value
  autoExpandParent.value = true
})

const getPatientTree = async () => {
  const res = await getPatientGroupUsingGet()
  if (res.data.code === 0 && res.data.data) {
    generateData(res.data.data ?? [])
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

const selectNode = (selectedKeys) => {
  groupId.value = selectedKeys[0]
  searchParams.groupId = selectedKeys[0]
  fetchData()
}

// 添加分组
const doAddGroup = async () => {
  const res = await addPatientGroupUsingPost(groupAddParams)
  if (res.data.code === 0 && res.data.data) {
    message.success('添加分组成功')
    getPatientTree()
  } else {
    message.error('添加分组失败，' + res.data.message)
  }
  addGroupFlag.value = false
}

const doUpdateGroup = async () => {
  const res = await updatePatientGroupUsingPost(groupUpdateParams)
  if (res.data.code === 0 && res.data.data) {
    message.success('更新分组成功')
    getPatientTree()
  } else {
    message.error('更新分组失败，' + res.data.message)
  }
  updateGroupFlag.value = false
}

// 展示更新弹窗
const showGroupUpdateModal = async () => {
  if (!groupId.value) {
    message.error('请选择分组')
    return
  }
  const res = await getPatientGroupByIdUsingGet({ id: groupId.value })
  if (res.data.code === 0 && res.data.data) {
    groupUpdateParams.id = res.data.data?.id ?? 0
    groupUpdateParams.parentId = res.data.data?.parentId ?? -1
    groupUpdateParams.groupName = res.data.data?.groupName ?? ''
  } else {
    message.error('获取分组信息失败，' + res.data.message)
  }

  updateGroupFlag.value = true
}

// 删除分组
const deleteGroup = async () => {
  if (!groupId.value) {
    message.error('请选择分组')
  } else {
    const res = await deletePatientGroupUsingPost({ id: groupId.value })
    if (res.data.code === 0 && res.data.data) {
      message.success('删除分组成功')
      groupId.value = undefined
      getPatientTree()
    } else {
      message.error('删除分组失败，' + res.data.message)
    }
  }
}
// ------------------------------- 病人表格 ------------------------------
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '病人名称',
    dataIndex: 'patientName',
  },
  {
    title: '所在分组',
    dataIndex: 'groupName',
  },
  {
    title: '预测状态',
    dataIndex: 'predictStatus',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '备注',
    dataIndex: 'note',
    width: '30%',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const searchParams = reactive<API.PatientQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
}) // 局部更新

// 定义数据
const dataTableList = ref<API.PatientVO[]>([]) //整体更新
const total = ref(0)

// 分页参数 (computed 监听值的变化情况，改变则更新)
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

const fetchData = async () => {
  const res = await listPatientVoByPageUsingPost({
    ...searchParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataTableList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

//表格变化，然后重新获取数据
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

const doTableDelete = async (id: number) => {
  const res = await deletePatientUsingPost({
    id: id,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('删除数据成功')
    fetchData()
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

const updatePatientParam = reactive<API.PatientUpdateRequest>({})
const selectedPatient = reactive<API.PatientVO>({})

const patientDetailFlag = ref(false)
//展示病人详情信息
const showPatientDetail = (record: API.PatientVO) => {
  Object.assign(selectedPatient, record)
  updatePatientParam.groupId = record.groupId
  updatePatientParam.id = record.id
  updatePatientParam.patientName = record.patientName
  updatePatientParam.note = record.note
  updatePatientFlag.value = true
  getVariables(record.filePredictVO?.trainId)
  patientDetailFlag.value = true
}

// 修改病人信息标志
const updatePatientFlag = ref(true)

const doPatientUpdate = async () => {
  const res = await updatePatientUsingPost(updatePatientParam)
  if (res.data.code === 0 && res.data.data) {
    message.success('更新数据成功数据成功')
    fetchData()
  } else {
    message.error('更新数据失败，' + res.data.message)
  }
  updatePatientFlag.value = true
}

const featureMap = ref<{ [key: string]: string }>({})
const targetMap = ref<{ [key: string]: string }>({})
const targetColumn = ref(0)
const variablesParamsList = ref<API.FilePredictOutputParams[]>([])
const getVariables = async (id) => {
  // 获取到id
  const res = await getFileVariablesListUsingPost({ trainId: id })
  if (res.data.code === 0 && res.data.data) {
    variablesParamsList.value = res.data.data.featureOutputParamsList
    // 使用 featureMap.value 来修改其值
    res.data.data.featureOutputParamsList.forEach((item: API.FilePredictOutputParams) => {
      featureMap.value[item.columnNumber] = item.variablesName
    })

    res.data.data.targetOutputParamsList.forEach((item: API.FilePredictOutputParams) => {
      targetMap.value[item.columnNumber] = item.variablesName
      targetColumn.value = item.columnNumber
    })
  }
}

// 创建病例参数
const addPatientParams = reactive<API.PatientAddRequest>({
  filePredictAddRequest: {
    predictParams: []
  }
})
const showAddPatientFlag = ref(false)

const showAddModal = () => {
  Object.assign(addPatientParams, {
    patientName: "",
    filePredictAddRequest: {
      predictParams: []
    },
    note: ""
  })
  addPatientParams.groupId = groupId.value
  showAddPatientFlag.value = true
}

const open = ref<boolean>(false)
const showDrawer = () => {
  // 初始化
  // 数据请求
  fetchTrainData()
  selectedTrainId.value = undefined
  open.value = true
}

const selectedTrainId = ref<Long>()

const onSubmit = () => {
  addPatientParams.filePredictAddRequest.trainId = selectedTrainId.value
  getPredictVariables()
  open.value = false
}

const onClose = () => {
  open.value = false
}

// -------------- 训练参数

const trainColumns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '文件id',
    dataIndex: 'fileId',
  },
  {
    title: '训练模型',
    dataIndex: 'model',
  },
  {
    title: '训练简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '文件名称',
    dataIndex: 'fileName',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const dataTrainList = ref<API.FileTrainVO[]>([]) //整体更新
const trainTotal = ref(0)
// 搜索条件
const searchTrainParams = reactive<API.FileTrainQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
}) // 局部更新

// 分页参数 (computed 监听值的变化情况，改变则更新)
const trainPagination = computed(() => {
  return {
    current: searchTrainParams.current,
    pageSize: searchTrainParams.pageSize,
    total: trainTotal.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})
const loginUserStore = useLoginUserStore()
const fetchTrainData = async () => {
  searchTrainParams.userId = loginUserStore.loginUser.id
  searchTrainParams.trainStatus = FILE_TRAIN_CREATE_STATUS_ENUM.SUCCESS
  const res = await listFileTrainVoByPageUsingPost({
    ...searchTrainParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataTrainList.value = res.data.data.records ?? []
    trainTotal.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

//表格变化，然后重新获取数据
const doTrainTableChange = (page: any) => {
  searchTrainParams.current = page.current
  searchTrainParams.pageSize = page.pageSize
  fetchTrainData()
}
// 搜索数据
const doTrainSearch = () => {
  // 重置页码
  searchTrainParams.current = 1
  fetchTrainData()
}

const variablesPredictParamsList = ref<API.FilePredictOutputParams[]>([])
const getPredictVariables = async () => {
  const id = addPatientParams?.filePredictAddRequest?.trainId
  if (id) {
    // 获取到id
    variablesPredictParamsList.value = []
    addPatientParams.filePredictAddRequest.predictParams = []
    const res = await getFileVariablesListUsingPost({ trainId: id })
    if (res.data.code === 0 && res.data.data) {
      variablesPredictParamsList.value = res.data.data.featureOutputParamsList
      // 使用 featureMap.value 来修改其值
      res.data.data.featureOutputParamsList.forEach((item: API.FilePredictOutputParams) => {

        addPatientParams.filePredictAddRequest.predictParams?.push({
          columnNumber: Number(item.columnNumber) - 1,
          param: null
        })
      })

    }
  } else {
    message.error("未选择训练模型")
  }
}

const doAddPatient = async () => {
  const res = await addPatientUsingPost(addPatientParams)
  if (res.data.code === 0 && res.data.data) {
    message.success("添加成功")
    fetchData()
  } else {
    message.error('添加失败，' + res.data.message)
  }
  showAddPatientFlag.value = false
}

// 页面加载时获取数据, 请求一次
onMounted(() => {
  getPatientTree()
  fetchData()
})
</script>
<style scoped>
#patientManagePage {
  max-width: 80%;
  margin: 0 auto;
}
</style>
